//
//  StatusViewModel.swift
//  新浪微博01
//
//  Created by 李国伟 on 15/12/11.
//  Copyright © 2015年 李国伟. All rights reserved.
//

import UIKit

///  单条微博模型
class StatusViewModel:CustomDebugStringConvertible {
 
    //拿到数据模型
    var status: Status
    
   ///  通过计算性属性来完成给cell的各个控件的属性的计算
    /// 用户头像 URL
    var profileURL: NSURL{
        
        let url = NSURL(string: status.user?.profile_image_url ?? "")
        
        return url!
    }
    /// 缩略图数组
    var thumbnailUrls: [NSURL]?
    
    /// 用户默认头像
    var userDefaultIcon: UIImage?{
        
        return UIImage(named: "avatar_default_big")
    }
    
    //cell的可重用标识符
    var reusedIdntify: String{
      
        return  self.status.retweeted_status != nil ? Statusretweeted: StatusNomal
    }
    
    //转发评论
    var retweetedText: String?{
        //判断是否为空
        guard let s = self.status.retweeted_status else{
            
            return nil
        }
        
        let string = "@" + (s.user?.screen_name ?? "") + ":" + (s.text ?? "")
        return string
    }
    
    //最重要的更改行高的计算方式
    lazy var rowHight: CGFloat = {
       
        let cell: StatusCell

        if self.status.retweeted_status == nil {
            
            cell = StatusNormalCell(style: .Default, reuseIdentifier: StatusNomal)
        }else{
            
            cell = StatusRetweetedCell(style: .Default, reuseIdentifier: Statusretweeted)
        }
//        let cell = StatusRetweetedCell(style: .Default, reuseIdentifier: Statusretweeted)
        return cell.rowHeight(self)
    }()
    
    /// 用户会员图标
    var membership: UIImage?{
        
        if status.user!.mbrank > 7 && status.user!.mbrank < 0 {
            
            return UIImage(named: "common_icon_membership_level\(status.user!.mbrank )")
        }
        
        return nil
    }
    /// 用户认证图标
    /// 认证类型，-1：没有认证，0，认证用户，2,3,5: 企业认证，220: 达人
    var verified : UIImage?{
        
        switch(status.user?.verified_type ?? -1){
            
        case 0: return UIImage(named: "avatar_vip")
        case 2, 3, 5: return UIImage(named: "avatar_enterprise_vip")
        case 220: return UIImage(named: "avatar_grassroot")
        default: return nil
        }
    }
    

   //自定义构造函数,完成赋值
    init(status: Status) {
        self.status = status
        var thumbnailUrl = [NSURL]()
        
        if let urls = status.retweeted_status?.pic_urls ?? status.pic_urls {
            //thumbnail_pic
            //遍历数组，数组必须保证有值
            for dic in urls {
                //value也是可选项，如果出错url将会为空
                let url = NSURL(string: dic["thumbnail_pic"]!)
                thumbnailUrl.append(url!)
            }
            thumbnailUrls = thumbnailUrl
        }
    }
    
    var debugDescription: String {
        return Status.description()
    }
}